import random
from datetime import timedelta, datetime
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import viewsets, status, serializers
from rest_framework.decorators import action
from rest_framework.response import Response

from home.models import VerifyCode
from home.serializers import VerifyCodeSerializer

# 验证码
@extend_schema_view(
    generic=extend_schema(
        summary='生成验证码',
        tags=['验证码'],
        description='生成验证码',
        request={'application/json': VerifyCodeSerializer,'application/x-www-form-urlencoded':VerifyCodeSerializer},
    )
)
class VerifyCodeViewSet(viewsets.ViewSet):
    # 生成验证码
    @action(methods=['post'], detail=False)
    def generic(self, request):
        # 手动调用序列化器
        serializer=VerifyCodeSerializer(data=request.data)
        if serializer.is_valid():
            # 随机生成6为纯数值验证码
            content=str(random.random())[2:8]
            # 过期时间
            expires = datetime.now() + timedelta(minutes=5)
            serializer.validated_data['content'] = content
            serializer.validated_data['expires'] = expires
            # 保存数据库
            serializer.save()
            return Response(data={'phone':serializer.validated_data.get('phone'),'content': content})
        raise serializers.ValidationError(serializer.errors)

